<template>
  <div class="user-container">
    <!-- 顶部操作栏 -->
    <BasicInformation
      title="新增用户"
      :primary-actions="actions"
      @action="handleAction"
    />

    <!-- 主表单 -->
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-card class="form-section">
        <template #header>
          <span class="section-title">用户信息</span>
        </template>

        <el-row :gutter="20">
          <!-- 账号 -->
          <el-col :md="12">
            <el-form-item label="账号" prop="account">
              <el-input
                v-model="form.account"
                placeholder="请输入账号"
                clearable
              />
            </el-form-item>
          </el-col>

          <!-- 姓名 -->
          <el-col :md="12">
            <el-form-item label="姓名" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入姓名"
                clearable
              />
            </el-form-item>
          </el-col>

          <!-- 密码 -->
          <el-col :md="12">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="form.password"
                type="password"
                placeholder="请输入初始密码"
                clearable
              />
            </el-form-item>
          </el-col>

          <!-- 性别 -->
          <el-col :md="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="form.sex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <!-- 公司 -->
          <el-col :md="24">
            <el-form-item label="公司" prop="company">
              <el-input
                v-model="form.company"
                placeholder="请输入公司"
                clearable
              />
            </el-form-item>
          </el-col>

          <!-- 职位（多选） -->
          <el-col :md="24">
            <el-form-item label="职位" prop="rids">
              <el-select
                v-model="form.rids"
                multiple
                placeholder="请选择职位"
                collapse-tags
              >
                <el-option
                  v-for="role in roles"
                  :key="role.id"
                  :label="role.name"
                  :value="role.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import BasicInformation from '@/public-view/BasicInformation.vue'
import type { Role } from '@/types/rs/User'
import request from '@/util/request'

const userInfo = sessionStorage.getItem('user');
const user = userInfo ? JSON.parse(userInfo) : null;

// 与后端 UserForm 保持一致
interface UserForm {
  id?: number
  account: string
  name: string
  password?: string
  sex: 1 | 2
  company: string
  rids: number[]
  createUser: string,
  updateUser: string,
}

// 表单数据
const form = reactive<UserForm>({
  account: '',
  name: '',
  password: '',
  sex: 1,
  company: '',
  rids: [],
  createUser: user.user.name,
  updateUser: user.user.name,
})

// 校验规则
const rules = reactive<FormRules<UserForm>>({
  account: [
    { required: true, message: '账号不能为空', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在3到20字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '姓名不能为空', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, message: '至少6位字符', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  company: [
    { required: true, message: '公司不能为空', trigger: 'blur' }
  ],
  rids: [
    { required: true, type: 'array', min: 1, message: '请至少选择一个职位', trigger: 'change' }
  ]
})

// 下拉选项：角色列表
const roles = ref<Role[]>([])

// 顶部按钮
const actions = [
  { name: 'save', label: '保存用户', type: 'primary' },
  { name: 'reset', label: '重置表单', type: 'warning' }
]

// 表单引用
const formRef = ref<FormInstance>()

// 加载角色选项
async function loadRoles() {
  try {
    const res = await request.get('per/role/getAll')
    roles.value = res.data.data || []
  } catch (err: any) {
    ElMessage.error('加载职位选项失败：' + err.message)
  }
}

onMounted(loadRoles)

// 按钮回调
function handleAction(action: string) {
  if (action === 'save') submitForm()
  else if (action === 'reset') resetForm()
}

// 提交
async function submitForm() {
  try {
    await formRef.value?.validate()
    const payload = { ...form }  // { account, name, password, sex, company, rids }
    const res = await request.post('per/user/add', payload)
    if (res.data.code === '200' || res.data.code === 200) {
      ElMessage.success(res.data.message || '添加成功')
      resetForm()
    } else {
      throw new Error(res.data.message)
    }
  } catch (err: any) {
    ElMessage.error(err.message || '提交失败')
  }
}

// 重置
function resetForm() {
  formRef.value?.resetFields()
  form.account = ''
  form.name = ''
  form.password = ''
  form.sex = 1
  form.company = ''
  form.rids = []
  ElMessage.info('表单已重置')
}
</script>

<style scoped>
.user-container { padding: 20px; }
.form-section { margin-bottom: 20px; }
.section-title { font-size: 16px; font-weight: 600; }
</style>
